<?php
/**
 * 用户服务
 * @author flaravel
 */
namespace App\Service;

use App\User;

class UserService
{

    //查找第三方openid是否已经注册过了，注册了则返回user信息，否则返回null
    public function checkRegister($openid = 0,$type = '',$unionid = 0)
    {
        $user = null;
        if ($type == 'wx_mini' || $type == 'wx_web') {
            //如果是小程序或者公众号登录
            if ($type == 'wx_mini') {
                $key = 'wx_mini_openid';
            } elseif ($type == 'wx_web') {
                $key = 'wx_web_openid';
            }
            if ($unionid) {
                //如果传入了unionid则先找unionid
                $user = User::where('wx_unionid', $unionid)->first();
                if ($user) {
                    //如果找到了，那就准备直接返回了，如果对应的openid为空
                    if (empty($user->$key)) {
                        $user->$key = $openid;
                        $user->save();
                    }
                    return $user;
                }
            }
            //没有通过unionid找到用户，那就再用openid找一次
            $user = User::where($key, $openid)->first();
        }

        return $user;
    }

    /**
     * 获取我的未过期且未使用的的优惠券
     *
     * @param User $user
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function getMyCoupons(User $user)
    {
        return $user->coupons()->begin()->use()->with('coupon')->get();
    }
}
